﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;

namespace Lan.ServiceCore.Signalr
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private readonly IHubContext<MessageHub> _messageHub;
        static ConcurrentQueue<string> _radarTargetQueue = new ConcurrentQueue<string>();
        public Worker(ILogger<Worker> logger, IHubContext<MessageHub> messageHub)
        {
            _logger = logger;
            _messageHub = messageHub;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {

                    string tarItem = "";
                    bool bl = _radarTargetQueue.TryDequeue(out tarItem);
                    if (bl)
                    {
                        await _messageHub.Clients.All.SendAsync("ReceiveTargetData", tarItem);
                        Console.WriteLine("ReceiveTargetData:发送成功");
                    }
                    await Task.Delay(100, stoppingToken);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error ReceiveTargetData");
            }
        }

        public static bool AddTarget(string receivedMessage)
        {
            _radarTargetQueue.Enqueue(receivedMessage);
            return true;
        }
    }
}
